import json

from channels.generic.websocket import AsyncWebsocketConsumer


class MessageConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        token = self.scope["url_route"]["kwargs"]["token"]
        group_name = 'group_{}'.format(token)
        await self.channel_layer.group_add(
            group_name,
            self.channel_name
        )
        await self.accept()

    async def disconnect(self, close_code):
        token = self.scope["url_route"]["kwargs"]["token"]
        group_name = 'group_{}'.format(token)
        await self.channel_layer.group_discard(
            group_name,
            self.channel_name
        )

    async def pay_notice(self, event):
        data = event['data']
        text_data = ''
        if type(data) == dict:
            text_data = json.dumps({
                'type': 'pay_notice',
                'data': data.get('msg', '')
            })
        await self.send(text_data=text_data)
